<template>
  <a-space direction="vertical">
    <a-card title="轮询规则配置">
      <a-form ref="searchRef" name="searchBar" :model="searchFormState" :labelCol="{ span: 5, offset: 1 }"
        @finish="handleSearch">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item name="pollingType" label="轮询类型">
              <a-input v-model:value="searchFormState.pollingType" placeholder=""></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" html-type="submit" :loading="searchLoading">搜索</a-button>
            <a-button style="margin: 0 8px" @click="() => searchRef?.resetFields()">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-space>
        <a-button @click="showModal" type="primary"><template #icon> <appstore-add-outlined /> </template>新增</a-button>
        <a-button @click="showEditModal"
          style="background-color: #f6ffed; color: #237804; border-color: #b7eb8f"><template #icon> <form-outlined />
          </template>修改</a-button>
        <a-button @click="showDelete" type="primary" danger><template #icon> <delete-outlined />
          </template>删除</a-button>
      </a-space>
    </a-card>
    <a-card title="查询结果">
      <a-table class="ant-table-striped" :rowClassName="
            (_record: any, index: number) => (index % 2 === 1 ? 'table-striped' : null)
          " :columns="columns" :data-source="data" rowKey="id" :loading="searchLoading" :rowSelection="rowSelection"
        @change="
            (pagination: any) => {
              handleSearch(pagination);
            }
          " :pagination="{
            position: [`bottomRight`],
            showSizeChanger: true,
            showQuickJumper: true,
            current: pageNum,
            pageSize,
            total: total,
            showTotal: (total: any) => `总计 ${total} 条记录`,
          }">
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'name'">
            <a>{{ text }}</a>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal ref="modalRef" v-model:visible="visible" @ok="handleOk" style="width: 1200px; top: 0">
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">
          {{ currentAction }}轮询规则
        </div>
      </template>
      <a-form ref="formRef" :model="formState" :labelCol="{ span: 5, offset: 1 }" name="form_in_modal">
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="pollingType" label="轮询类型" :rules="[{ required: true, message: '请输入轮询类型' }]">
              <a-input v-model:value="formState.pollingType" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="startTime" label="开始时间点" :rules="[{ required: true, message: '请输入开始时间点' }]">
              <!-- 使用时间选择组件 -->
              <a-time-picker v-model:value="formState.startTime" value-format="HH:mm" :show-second="false"
                placeholder="请选择开始时间点" style="width: 100%" />                
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="endTime" label="截至时间点" :rules="[{ required: true, message: '请输入截至时间点' }]">
              <!-- 使用时间选择组件 -->
              <a-time-picker v-model:value="formState.endTime" value-format="HH:mm" :show-second="false"
                placeholder="请选择截至时间点" style="width: 100%" />                
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="pollingFrequency" label="轮询频次" :rules="[
              { required: true, message: '请输入轮询频次' },
              // 自定义正则校验：仅允许数字（整数），适配字符串类型
              { pattern: /^[1-9]\d*$/, message: '请输入正整数' }
            ]">
              <a-input v-model:value="formState.pollingFrequency" type="number" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-space>
</template>
  <script lang="ts" setup>
  // base library
  import { LISTHEADER } from "./config"; // 从同级config.ts文件中导入表头
  import { listQuery, add, edit, del} from "@/api/pmManagement/pmPollingRole/pmPollingRole";
  import { onMounted } from "@vue/runtime-core";
  import {
    computed,
    createVNode,
    reactive,
    ref,
    toRaw,
    unref
  } from "vue";
  import { FormInstance, message, Modal } from "ant-design-vue";
  import { useDraggable } from "@vueuse/core";
  import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
  import dayjs,{ Dayjs } from "dayjs";
  
  const searchRef = ref<FormInstance>();
  let searchLoading = ref(true);
  const searchFormState: { [propName: string]: any } = reactive({});
  
  const columns = LISTHEADER;
  let pageNum = ref(1);
  let pageSize = ref(10);
  let total = ref(0);
  let data = ref([]);
  const handleSearch = (values?: any) => {
    searchLoading.value = true;
    console.log("Received values of form: ", values);
    console.log("searchFormState: ", searchFormState);
    let parameter = { ...searchFormState };
    if (values?.current) {
      // 分页切换
      pageNum.value = values?.current;
      pageSize.value = values?.pageSize;
    } else {
      // 搜索
      selectedRowKeys.value = [];
      selectedRows.value = [];
      pageNum.value = 1;
    }
    const requestParameters = Object.assign({}, parameter, {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
    console.log("loadData request parameters:", requestParameters);
  
    // 列表查询及条件查询
    listQuery(requestParameters).then(
      (res: {
        code: number | string;
        msg: string;
        total: number;
        rows: any;
      }) => {
        console.log("打印完整的返回信息：" + res);
        searchLoading.value = false;
        const { code, msg, total: count, rows } = res;
        console.log("接口编码：" + code);
        console.log("接口信息：" + JSON.stringify(rows, null, 2))
        if (code === 200) {
          data.value = rows;
          total.value = count;
        } else {
          total.value = 0;
          data.value = [];
          pageNum.value = 1;
          message.error(msg);
        }
      }
    );
  };
  type T = any  
  // 查询出的数据表单展示后，选择数据，对选中的数据进行赋值
  const selectedRowKeys = ref<string[]>([]); // 一般存放选中数据的id，由rowKey控制，rowKey取啥字段就存啥字段的值
  const selectedRows = ref<T[]>([]); // 存放选中行的所有数据
  const onSelectChange = (changableRowKeys: string[], changableRows: T[]) => {
    console.log("选中的行ID:", selectedRowKeys);
    console.log("选中的行数据:", selectedRows);
    console.log("selectedRowKeys changed: ", changableRowKeys);
    selectedRowKeys.value = changableRowKeys;
    selectedRows.value = changableRows;
  };
  const rowSelection = computed(() => {
    return {
      selectedRowKeys: unref(selectedRowKeys),
      onChange: onSelectChange,
      hideDefaultSelections: false,
    };
  });
  enum action {
    add = "新增",
    edit = "编辑",
  }
  const currentAction = ref(action.add);
  const visible = ref<boolean>(false);
  const modalTitleRef = ref<HTMLElement>();
  
  const { x, y, isDragging } = useDraggable(modalTitleRef);
  const startX = ref<number>(0);
  const startY = ref<number>(0);
  const startedDrag = ref(false);
  const transformX = ref(0);
  const transformY = ref(0);
  const preTransformX = ref(0);
  const preTransformY = ref(0);
  const dragRect = ref({ left: 0, right: 0, top: 0, bottom: 0 });
  
  // 表单字段定义，一般是弹窗中的表单
  interface FormValues {
    id: string;
    pollingType: string;
    startTime: Date | null;
    endTime: Date | null;
    pollingFrequency: string;
    remarks: string;

  }
  const formRef = ref<FormInstance>();
  const formState = reactive<FormValues>({ // 表单数据初始化
    id: "",
    pollingType: "",
    startTime: null,    
    endTime: null,
    pollingFrequency: "",
    remarks: "",
  });
  // 备份初始化为空的表单数据，用于新增按钮时置空可能存在的遗留表单数据
  const formBackup = { ...formState };
  const reset = () => {
    formRef.value?.resetFields();
    Object.assign(formState, formBackup);
  }
  // 新增弹窗页面，并对表单数据进行初始化为空，防止出现先打开编辑弹窗后，遗留表单数据
  const showModal = () => {
    reset();
    formState.id = "";//resetFields() 对 id 字段无效！因为弹窗表单中没有 id 对应的表单控件,手动重置id，双重保障
    visible.value = true;
    currentAction.value = action.add;
  };
  // 编辑弹窗页面
  const showEditModal = () => {
    if (selectedRowKeys.value.length > 1)
      message.error("仅能选择一条记录进行操作");
    if (selectedRowKeys.value.length === 0)
      message.error("请选择一条记录进行操作");
    if (selectedRowKeys.value.length === 1) {
      currentAction.value = action.edit;
      visible.value = true;
      formRef.value?.resetFields();
      Object.assign(formState, selectedRows.value[0]);
    }
  };
  // 弹窗页面中确定按钮点击事件，由于新增和修改共用一个弹窗页面，故可以在此方法中判断新增和更新方法
  const handleOk = (e: MouseEvent) => {
    console.log(e);
    // visible.value = false;
    formRef.value
      .validateFields()
      .then((values) => {
        console.log("Received values of form: ", values);
        console.log("formState: ", toRaw(formState));
        visible.value = false;
        // 当前action为add时，调用新增方法add
        if (currentAction.value === action.add) {
          add(formState).then((res) => {
            const { code, msg } = res;
            if (code === 200) {
              Modal.success({
                title: msg,
              });
              formRef.value?.resetFields();
              console.log("reset formState: ", toRaw(formState));
            } else {
              Modal.error({
                title: msg,
              });
            }
            handleSearch();
          });
        }
        // 当前action为edit时，调用编辑方法edit
        if (currentAction.value === action.edit) {
          edit(formState).then((res) => {
            const { code, msg } = res;
            if (code === 200) {
              Modal.success({
                title: msg,
              });
              formRef.value?.resetFields();
              console.log("reset formState: ", toRaw(formState));
            } else {
              Modal.error({
                title: msg,
              });
            }
            handleSearch();
          });
        }
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });
  };
  // 删除弹窗页面，选中数据后，点击删除，调用del删除方法
  const showDelete = () => {
    if (selectedRowKeys.value.length === 0){
      message.error("请选择一条记录进行操作");
    } else {
      Modal.confirm({
        title: "请确认是否操作删除?",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "删除",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          console.log("selectedRows: ", toRaw(selectedRows.value[0]).id,selectedRows);
          del(selectedRowKeys.value).then((res) => {
            const { code, msg } = res;
            if (code === 200) {
              console.log("resp: ", toRaw(res));
              Modal.success({
                title: msg,
              });
              handleSearch();
            } else {
              Modal.error({
                title: msg,
              });
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    }
  };
  onMounted(() => {
    searchLoading.value = false;
    //   handleSearch();
  });
  </script>
  <script lang="ts">
  import {
    AppstoreAddOutlined,
    FormOutlined,
  } from "@ant-design/icons-vue";

  import {
    TimePicker  // 必须导入TimePicker组件
  } from "ant-design-vue";
    
  export default {
    name: "pmPollingRole",
    components: {
      AppstoreAddOutlined,
      FormOutlined,
      ATimePicker: TimePicker
    },
  };
  </script>
  
  <style type="less" scoped>
  /* .ant-form-item-label > label {
    width:150px!important;
    justify-content: end!important;
  } */
  .ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
  }
  
  </style>
  